package packets;

import java.util.ArrayList;
import java.util.List;

import org.jnetpcap.nio.JBuffer;
import org.jnetpcap.packet.JHeader;
import org.jnetpcap.packet.JPacket;
import org.jnetpcap.packet.JRegistry;
import org.jnetpcap.packet.RegistryHeaderErrors;
import org.jnetpcap.packet.annotate.Bind;
import org.jnetpcap.packet.annotate.Field;
import org.jnetpcap.packet.annotate.Header;
import org.jnetpcap.packet.annotate.HeaderLength;

/**
 * Diese Klasse repräsentiert das OSPF Link State Update Paket und enthält Methoden, die die entsprechenden Felder zurück geben.
 * @author pascal
 *
 */
@Header
public class OSPFUpdate extends JHeader {
	
	private List<LSA> lsaList = new ArrayList<LSA>();
	
	public List<LSA> getLSAs(){
		return lsaList;
	}
	
	
	@HeaderLength
	public static int headerLength(JBuffer buffer, int offset){
		return buffer.size() - offset;
	}
	
	@Bind(to=OSPF.class)
	public static boolean bindToOSPF(JPacket packet, OSPF ospf){
		return ospf.type() == 0x04;
	}
	
	@Field(offset=0, length=4)
	public long numberOfLSAs(){
		return getUInt(0);
	}
	
	/**
	 * Dekodiert den Speicherbereich des Pakets und findet die in diesem Paket enthaltenen LSAs.
	 */
	@Override
	protected void decodeHeader() {
		int offsetIntoHeader = 4;
		int bytesRemaining= this.size() - offsetIntoHeader;
		
		// Erzeuge LSA Header um zu prüfen um Welche LSA sich handelt. Dann wird die eigentliche LSA erzeugt.
		while(bytesRemaining > 0){
			LSA tempLSA = new LSA();
			tempLSA.peer(this, offsetIntoHeader, 20);
			int lengthOfLSA = tempLSA.length();
			
			// Router LSA gefunden
			if(tempLSA.type() == 0x01){
				tempLSA = new RouterLSA(this, lengthOfLSA, offsetIntoHeader);
				bytesRemaining = bytesRemaining - lengthOfLSA;
				offsetIntoHeader = offsetIntoHeader + lengthOfLSA;
				lsaList.add(tempLSA);
			}
			// Network LSA gefunden
			else if(tempLSA.type() == 0x02){
				tempLSA = new NetworkLSA(this, lengthOfLSA, offsetIntoHeader);
				bytesRemaining = bytesRemaining - lengthOfLSA;
				offsetIntoHeader = offsetIntoHeader + lengthOfLSA;
				lsaList.add(tempLSA);
			}
			else System.out.println("Unknown LSA type received");
		}
				
	}
	
	static {
		try {
			JRegistry.register(OSPFUpdate.class);
		}catch(RegistryHeaderErrors e){
			e.printStackTrace();
		}
	}

}
